package com.yh.autobio.modules.ui;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.design.widget.Snackbar;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.yh.autobio.AppConfig;
import com.yh.autobio.AppContext;
import com.yh.autobio.R;
import com.yh.autobio.api.RetrofitSingleton;
import com.yh.autobio.base.BaseActivity;
import com.yh.autobio.common.PLog;
import com.yh.autobio.common.TDevice;
import com.yh.autobio.modules.bean.Contact;
import com.yh.autobio.modules.bean.Result;
import com.yh.autobio.modules.bean.Token;

import butterknife.InjectView;
import butterknife.OnClick;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * 用户登录界面
 *
 * @author imyar
 */
public class LoginActivity extends BaseActivity {

    public static final int REQUEST_CODE_INIT = 0;
    private static final String BUNDLE_KEY_REQUEST_CODE = "BUNDLE_KEY_REQUEST_CODE";
    protected static final String TAG = LoginActivity.class.getSimpleName();

    @InjectView(R.id.et_username)
    EditText mEtUserName;
    @InjectView(R.id.et_password)
    EditText mEtPassword;
    @InjectView(R.id.cb_loginRemember)
    CheckBox cb_loginRemember;
    private final int requestCode = REQUEST_CODE_INIT;
    private String mUserName = "";
    private String mPassword = "";
    int count = 0;//登录环信聊天服务器超时判断，如果超时，则不登录
    private SharedPreferences mSp;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        AppContext.getInstance().clear();
    }

    @Override
    protected boolean hasBackButton() {
        return true;
    }

    @Override
    protected int getActionBarTitle() {
        return R.string.login;
    }

    @Override
    @OnClick({R.id.btn_login, R.id.iv_forget_pwd})
    public void onClick(View v) {

        int id = v.getId();
        switch (id) {
            case R.id.btn_login:
                handleLogin();
//                handleLoginSuccess();
                break;
            case R.id.iv_forget_pwd:
//                UIHelper.showRegisterActivity(this, 2,"Find","找回密码");
                break;
            default:
                break;
        }
    }

    private void handleLogin() {

        if (prepareForLogin()) {
            return;
        }
        // if the data has ready
        mUserName = mEtUserName.getText().toString();
        mPassword = mEtPassword.getText().toString();

        showWaitDialog(R.string.progress_login);
        Contact mContact = new Contact();
        mContact.setUsername(mUserName);
        mContact.setPwd(mPassword);
        RetrofitSingleton.clearApiService();

        RetrofitSingleton.getApiService(this).
                login(mContact)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    Observer<Result> observer = new Observer<Result>() {
        @Override
        public void onCompleted() {
            PLog.d("s", "onCompleted");
            hideWaitDialog();
        }

        @Override
        public void onError(Throwable e) {
            PLog.d("s", e.getMessage());
            Snackbar.make(getWindow().getDecorView(), "" + e.getMessage(), Snackbar.LENGTH_SHORT).show();
            hideWaitDialog();
        }

        @Override
        public void onNext(Result result) {
            hideWaitDialog();
            if (result.isSuccess()) {
                Gson gson = new Gson();
                String json = gson.toJson(result.getData());
                Token token = new Gson().fromJson(json, Token.class);

                if (token != null) {
                    AppContext.getInstance().setCurrentUser(token.getUserInfo());
                    AppContext.getInstance().saveLoginInfo(token.getUserInfo());
                    AppContext.getInstance().setProperty("user.account", mUserName);
                    AppContext.getInstance().setProperty("user.pwd", mPassword);
                    AppContext.getInstance().setProperty("user.id", token.getUserInfo().getId());

                    AppContext.getInstance().setProperty(AppConfig.PRIVATE_TOKEN, token.getSToken());

                    handleLoginSuccess();
                } else {
                    Snackbar.make(getWindow().getDecorView(), "解析错误", Snackbar.LENGTH_SHORT).show();
                }
            } else {
                Snackbar.make(getWindow().getDecorView(), "用户名或密码错误", Snackbar.LENGTH_SHORT).show();
            }
        }
    };

    private void handleLoginSuccess() {
        Intent main = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(main);
        if (LoginActivity.this != null && !LoginActivity.this.isFinishing()) {
            hideWaitDialog();
        }
        finish();
    }

    private boolean prepareForLogin() {
        if (!TDevice.hasInternet()) {
            Snackbar.make(mEtPassword, R.string.tip_no_internet, Snackbar.LENGTH_SHORT).show();
            return true;
        }
        if (mEtUserName.length() == 0) {
            mEtUserName.setError("请输入用户名");
            mEtUserName.requestFocus();
            return true;
        }

        if (mEtPassword.length() == 0) {
            mEtPassword.setError("请输入密码");
            mEtPassword.requestFocus();
            return true;
        }

        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void initData() {
        String account = AppContext.getInstance().getProperty("user.account");
        mEtUserName.setText(account);
        String pwd = AppContext.getInstance().getProperty("user.pwd");
        mEtPassword.setText(pwd);
        mEtPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i== EditorInfo.IME_ACTION_DONE){
                    handleLogin();
                }
                return false;
            }
        });
    }
}
